package com.wk.warehouse.controller;

import java.util.List;
import com.wk.warehouse.entity.OutStore;
import com.wk.warehouse.entity.Result;
import com.wk.warehouse.service.OutStoreService;
import com.wk.warehouse.service.ProductService;
import com.wk.warehouse.service.StoreService;
import com.wk.warehouse.page.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 出库管理后台
 */
@RestController
@RequestMapping("/outstore")
public class OutstoreController {

	@Autowired
	private OutStoreService outStoreService;
	@Autowired
	private StoreService storeService;
	@Autowired
	private ProductService productService;

	/**
	 * 所有仓库
	 */
	@GetMapping("/store-list")
	public Result storeList() {
		return Result.ok(storeService.storeList());
	}

	/**
	 * 分页模糊查询所有出库单
	 */
	@GetMapping("/outstore-page-list")
	public Result outStorePageList(OutStore outStore, Page page) {
		// 获取总条数
		int totalNum = outStoreService.selectCount(outStore);
		page.setTotalNum(totalNum);

		List<OutStore> outStoreList = outStoreService.selectOutStorePage(outStore, page);
		page.setResultList(outStoreList);
		return Result.ok(page);
	}

	/**
	 * 导出数据
	 */
	@GetMapping("/exportTable")
	public Result exportTable(OutStore outStore, Page page){
		page = new Page(9999, 1); // 导出模糊查询所有数据
		// 要导出的数据
		List<OutStore> outStoreList = outStoreService.selectOutStorePage(outStore, page);
		return Result.ok(outStoreList);
	}

	/**
	 * 用户申请出库
	 */
	@PostMapping("/outstore-add")
	public Result addOutstore(@RequestBody OutStore outStore) {
		// 库存
		Integer productInvent = productService.findProductInvent(outStore.getProductId());
		// 申请出库数量大于库存
		if(productInvent==null || outStore.getOutNum()>productInvent){
			return Result.err(Result.CODE_ERR_BUSINESS, "库存不足！");
		}
		outStoreService.requestOutStore(outStore);
		return Result.ok("申请出库成功");
	}

	/**
	 * 确定出库
	 */
	@PutMapping("/outstore-confirm")
	public Result confirmOutstore(@RequestBody OutStore outStore) {
		// 库存
		Integer productInvent = productService.findProductInvent(outStore.getProductId());
		// 出库单数量大于库存
		if(productInvent==null || outStore.getOutNum()>productInvent){
			return Result.err(Result.CODE_ERR_BUSINESS, "库存不足！");
		}
		// 库存足够，更新库存
		outStoreService.updateStoreNum(outStore);
		// 修改出库状态
		outStoreService.updateOutStoreState(outStore.getOutsId());
		return Result.ok("出库成功！");
	}
}

